<?php
/**
 * Created by PhpStorm.
 * User: 2016-08-23
 * Date: 2017/11/6
 * Time: 10:46
 */
$api_service_path = __DIR__ . "/../../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 
/**
 * 用于金蝶推送账套的脚本 主要用处出入库的推送  第一个执行
 *
 */

// $mdb=MaintenanceShops::where("status",1)->get();//循环各个门店的入库出库各种记录
// $_date=array(date('Y-m-01', strtotime('-1 month')),date('Y-m-t', strtotime('-1 month')));

// $mdb=MaintenanceShops::where("status",1)->where("id","!=",5)->get();
// $mdb=MaintenanceShops::whereIn("id",array(1))->get();
// $_date=array("2018-07-01","2018-07-31");
// $mdb=MaintenanceShops::whereIn("id",array(1))->get();//循环各个门店的入库出库各种记录
// $_date=array("2018-02-11","2018-02-11");
$mdb=MaintenanceShops::where("status",1)->where("id","!=",5)->get();//循环各个门店的入库出库各种记录
$c_date=date('Y-m-d',time()-86400);//前一天
$_date=array($c_date,$c_date);
// $_date=array("2018-09-17","2018-09-17");

Log::useFiles(storage_path().'/logs/kingdee_push.log');

        
$cur_date=floor((strtotime($_date[1])-strtotime($_date[0]))/86400);
for($i=0;$i<=$cur_date;$i++){   
    $date=date('Y-m-d',strtotime($_date[0])+$i*86400);   
    foreach ($mdb as $_mdb) {//
        if(!$_mdb->kingdee_groupid){
            continue;
        }
        $tkvs=KingdeeVoucherStatus::where("date",$date)->where("type","supply_inout")->where("shop_id",$_mdb->id)->where("status",1)->first();
        if($tkvs){//如果该门店 该天已经推送过凭证了
            continue;
        }

        $data=array('mainVoucher' =>
            array(
                    
            )
        );
        $entty_array=array();//组织所有的最基层 结构
        $inputjie = array(
            "FAccountID"=>"1243",
            "FExplanation"=>"",
            "FCurrencyID"=>1,
            "FExchangeRate"=>1,
            "FDC"=>1,
            "FAmountFor"=>100,
            "FAmount"=>100,
            "data"=>array(
                "009"=>"114",//商品分类
                "012"=>"001",//直营店
            ),
        );
        $inputdai = array(
            "FAccountID"=>"1243",
            "FExplanation"=>"脚本测试1",
            "FCurrencyID"=>1,
            "FExchangeRate"=>1,
            "FDC"=>0,
            "FAmountFor"=>100,
            "FAmount"=>100,
            "data"=>array(
                "009"=>"114",//商品分类
                "012"=>"001",//直营店
            ),
        );
        $datejie=array();
        $datedai=array();

        $begin_date=date("Y-m-d H:i:s",strtotime($date." 00:00:00")-Config::get("config.report_time_diff"));
        $end_date=date("Y-m-d H:i:s",strtotime($date." 23:59:59")-Config::get("config.report_time_diff"));
        $xj_msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
        if(is_null($xj_msk)){
            Log::error("门店 ".$_mdb->id."现金科目异常");
            continue 1;//有错误数据
        }
        /**
         *
         *
         * 查找该用户改天的入库记录   
         */ 
        $xj_storage_entty_array=array();
        $xj_storage_key_array=array();
        $gz_storage_entty_array=array();
        $gz_storage_key_array=array();
        $storage=DB::select("SELECT maintenance_storage_list.id,maintenance_storage_list.methed,maintenance_storage_list.consuming_id,maintenance_storage_list.shop_type,maintenance_storage_list.user_type,maintenance_storage_list.type,maintenance_storage_list.supplier,maintenance_storage_list.storage_type,DATE_FORMAT(maintenance_storage_list.implement_time,   '%m-%d') as implement_time,maintenance_storage_list.pay_type,maintenance_shops.kingdee_shopnum,maintenance_supplier.kingdee_supper,maintenance_supplier.name as supplier_name
            FROM maintenance_storage_list
            LEFT JOIN maintenance_shops ON maintenance_shops.id = maintenance_storage_list.shop_id
            LEFT JOIN maintenance_supplier ON maintenance_supplier.id = maintenance_storage_list.supplier
            WHERE `maintenance_storage_list`.`shop_id` = ?
            AND `maintenance_storage_list`.`implement_time` BETWEEN ?
            AND ?                
            AND `maintenance_storage_list`.`status` = 1
            AND `maintenance_storage_list`.`type` IN (1, 2)
            ORDER BY
                `maintenance_storage_list`.`implement_time` ASC", array($_mdb->id,$begin_date, $end_date ));

        foreach ($storage as $_sto) {//循环入库记录 组织结构     
            $inputdai["FDC"]=0;         
            if($_sto->type==1) {//确定是批量临时 还是领用归还
                if($_sto->storage_type==4){//入库方式 批量临时 只会有  0购入 1调入 4盘盈三种入库方式 如果是盘盈
                    $inputjie["FAccountID"]="1243";
                    $inputjie["FExplanation"]=$_sto->implement_time." 正库存调整";
                    $inputdai["FExplanation"]=$_sto->implement_time." 正库存调整";
                    $inputdai["FDC"]=1;
                    $inputdai["FAccountID"]="5501.19";
                    $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);
                    $datedai=array("012"=>$_sto->kingdee_shopnum);
                }else if($_sto->storage_type==0){//如果是 购入                       
                    if($_sto->pay_type==0){//现金
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $inputdai["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
                        if(is_null($msk)){
                            Log::error("门店 ".$_mdb->id."现金科目异常");
                            continue 2;//有错误数据
                        }
                        $inputdai["FAccountID"]=$msk->acount;
                        $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);
                        $datedai=array();
                    }else if($_sto->pay_type==2){//挂账
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $inputdai["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $inputdai["FAccountID"]="2121";
                        $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);//借方 分类和 直营店
                        $datedai=array("008"=>$_sto->kingdee_supper,"012"=>$_sto->kingdee_shopnum);//供应商  直营店
                    }else{
                        continue;//本单 不推凭证
                    }
                }else{//如果是 调入
                    if($_sto->pay_type==2){//如果是 挂账
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $inputdai["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        // $msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
                        // if(is_null($msk)){
                        //  Log::error("门店 ".$_mdb->id."现金科目异常");
                        //  break 2;//有错误数据
                        // }
                        // $inputdai["FAccountID"]=$msk->acount;
                        // $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);
                        // $datedai=array();
                        $inputdai["FAccountID"]="2121";
                        $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);//借方 分类和 直营店
                        $datedai=array("008"=>$_sto->kingdee_supper,"012"=>$_sto->kingdee_shopnum);//供应商  直营店
                    }else{
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $inputdai["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                        $msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
                        if(is_null($msk)){
                            Log::error("门店 ".$_mdb->id."现金科目异常");
                            continue 2;//有错误数据
                        }
                        $inputdai["FAccountID"]=$msk->acount;
                        $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);
                        $datedai=array();                       
                    }
                }           
            }else{//是领用归还
                $temp_supplier="";
                if($_sto->methed==1){
                    $department=Department::find($_sto->consuming_id);
                    $temp_supplier=$department->kingdee_suppliernum;
                }elseif($_sto->methed==3){
                    if($_sto->shop_type==1){
                        if($_sto->user_type=1){
                            $sc=SCUser::find($_sto->consuming_id);
                            $ms=MaintenanceShops::find($sc->shop_id);
                            $temp_supplier=$ms->kingdee_suppliernum;
                        }else{
                            $me=MaintenanceEngineers::find($_sto->consuming_id);
                            $ms=MaintenanceShops::find($me->type_id);
                            $temp_supplier=$ms->kingdee_suppliernum;
                        }
                    }else{
                        $department=Department::find($_sto->consuming_id);
                        $temp_supplier=$department->kingdee_suppliernum;
                    }
                }else{
                    $ms=MaintenanceShops::find($_sto->consuming_id);
                    $temp_supplier=$ms->kingdee_suppliernum;
                }

                $inputjie["FAccountID"]="1243";
                $inputjie["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                $inputdai["FExplanation"]=$_sto->implement_time." ".$_sto->supplier_name." 配件入库";
                $inputdai["FAccountID"]="2121";
                $datejie=array("009"=>"","012"=>$_sto->kingdee_shopnum);//借方 分类和 直营店
                $datedai=array("008"=>$temp_supplier,"012"=>$_sto->kingdee_shopnum);//供应商  直营店
            }
            //如果领用归还 和批量临时不同 把本段代码挪到  批量临时判断分支 
            $count=DB::select("SELECT sc1.id,sc1.`name`,sc1.jindie_code,sum(msi.tax_purchase_subtotal) as amount
                FROM `maintenance_storage_item` msi
                LEFT JOIN supply_item si ON msi.item_id = si.id
                LEFT JOIN supply_classification sc3 ON sc3.id = si.supply_classification_id
                LEFT JOIN supply_classification sc2 ON sc2.id = sc3.parent_id
                LEFT JOIN supply_classification sc1 ON sc1.id = sc2.parent_id
                WHERE list_id = ? and msi.status=1 group by sc1.id",array($_sto->id));
            $temp_storage_array=array();
            foreach ($count as $_count) {                
                if($_sto->type==1&&$_sto->storage_type==4){
                    if($_count->amount==0){
                        continue;
                    }
                    $inputjie["FAmountFor"]=round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=round($_count->amount/100,2);
                    $datejie["009"]=$_count->jindie_code;
                    $inputjie["data"]=$datejie;
                    $temp_storage_array[]=$inputjie;
                    $inputdai["FAmountFor"]=-round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=-round($_count->amount/100,2);
                    $inputdai["data"]=$datedai;
                    $temp_storage_array[]=$inputdai;
                }else{
                    if($_count->amount==0){
                        continue;
                    }
                    $inputjie["FAmountFor"]=round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=round($_count->amount/100,2);
                    $datejie["009"]=$_count->jindie_code;
                    $inputjie["data"]=$datejie;
                    $temp_storage_array[]=$inputjie;
                    $inputdai["FAmountFor"]=round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=round($_count->amount/100,2);
                    $inputdai["data"]=$datedai;
                    $temp_storage_array[]=$inputdai;
                }
            }

             //合并 入库单贷方
            $depe_temp_dai=null;
            foreach($temp_storage_array as $key=>$t){
                if($t['FDC']==0){
                    if(is_null($depe_temp_dai)){
                        $depe_temp_dai=$t;
                    }else{
                        $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                        $depe_temp_dai["FAmount"]+=$t['FAmount'];
                    }
                    unset($temp_storage_array[$key]);
                }
            }
            if(!is_null($depe_temp_dai)){
                $temp_storage_array[]=$depe_temp_dai;
            }
            if(sizeof($temp_storage_array)==0){
                continue;
            }
            if($_sto->pay_type==0||($_sto->type==1&&$_sto->storage_type==4&&$_sto->pay_type==3)){//现金
                $xj_storage_entty_array[$_sto->id]=$temp_storage_array;
                $xj_storage_key_array[$_sto->id]=sizeof($temp_storage_array);           
            }else if($_sto->pay_type==2){
                $gz_storage_entty_array[$_sto->id]=$temp_storage_array;
                $gz_storage_key_array[$_sto->id]=sizeof($temp_storage_array);
            }
        }
        $data=assemble($data,$xj_storage_entty_array,$xj_storage_key_array,$date,$_mdb);
        $data=assemble($data,$gz_storage_entty_array,$gz_storage_key_array,$date,$_mdb);
        unset($xj_storage_entty_array);
        unset($gz_storage_entty_array);
        unset($xj_storage_key_array);
        unset($gz_storage_key_array);
        /**
         *
         *
         * 查找该用户改天的入库记录 完毕   
         */ 
        /**
         *
         *
         * 查找该店该天的出库数据
         */         
        
        $out_entty_array=array();
        $out_key_array=array();
        $out_list=DB::select("SELECT    maintenance_out_list.id,DATE_FORMAT(maintenance_out_list.implement_time,   '%m-%d') as implement_time,maintenance_out_list.consuming_type,maintenance_out_list.methed,maintenance_out_list.type,maintenance_out_list.shop_type,maintenance_out_list.consuming_id,maintenance_out_list.pay_type,maintenance_out_list.return_type,ms.kingdee_supper
            FROM `maintenance_out_list`
            LEFT JOIN maintenance_supplier ms on ms.id= maintenance_out_list.consuming_id
            WHERE maintenance_out_list.shop_id = ?
            AND maintenance_out_list.implement_time BETWEEN ?
            AND ?
            AND maintenance_out_list.`status` = 1
            AND maintenance_out_list.type IN (1,2)
            ORDER BY
                `maintenance_out_list`.`implement_time` ASC", array($_mdb->id,$begin_date, $end_date));
        foreach ($out_list as $_out_list) {//循环入库记录 组织结构
            $inputdai["FDC"]=0;
            $temp_type=0;
            if($_out_list->type==1){//如果是 内部领用
                if($_out_list->methed==1){//如果是 领用                          
                    $msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","5501.06")->first();//本门店的营业费用科目
                    if(is_null($msk)){
                        Log::error("门店 ".$_mdb->id."营业费用科目异常");
                        continue 2;//有错误数据
                    }
                    $inputjie["FAccountID"]=$msk->acount;
                    $inputjie["FExplanation"]=$_out_list->implement_time." 物料领用出库";
                    $inputdai["FExplanation"]=$_out_list->implement_time." 物料领用出库";
                    $inputdai["FAccountID"]="1243";
                    $datejie=array("012"=>$_mdb->kingdee_shopnum);//借方  直营店
                    $datedai=array("009"=>"","012"=>$_mdb->kingdee_shopnum);//分类和  直营店
                    $temp_type=1;
                }else if($_out_list->methed==2){//如果是 调出     
                    // $_out_list->consuming_id  此种方式领用人就是领用的人 就是门店id  找产品确认是不是记录这个门店信息                 
                    $msk=MaintenanceShopKingdee::where("shop_id",$_out_list->consuming_id)->where("code","1291")->first();//本门店的 
                    if(is_null($msk)){
                        Log::error("门店 ".$_out_list->consuming_id." 科目异常");
                        continue 2;//有错误数据
                    }
                    $dc_mdb=MaintenanceShops::find($_out_list->consuming_id);
                    $inputjie["FAccountID"]=$msk->acount;
                    $inputjie["FExplanation"]=$_out_list->implement_time." ".$dc_mdb->name." 外调";
                    $inputdai["FExplanation"]=$_out_list->implement_time." ".$dc_mdb->name." 外调";
                    $inputdai["FAccountID"]="1243";
                    if($msk->acount=='1291.10'){//如果是汽配不需要门店
                        $datejie=array();//借方  直营店
                    }else{
                        $datejie=array("012"=>$_mdb->kingdee_shopnum);//借方  直营店
                    }                    
                    $datedai=array("009"=>"","012"=>$_mdb->kingdee_shopnum);//分类和  直营店
                    $temp_type=2;
                }else{
                    continue;//本单 不推凭证
                }
            }else{//如果是出库退货
                if($_out_list->return_type==0){ //如果是退货挂账
                    $ms=MaintenanceSupplier::find($_out_list->consuming_id);
                    if($_out_list->pay_type==2){                        
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_out_list->implement_time." ".$ms->name." 配件入库，退货";
                        $inputdai["FExplanation"]=$_out_list->implement_time." ".$ms->name." 配件入库，退货";
                        $inputdai["FAccountID"]="2121";
                        $datejie=array("009"=>"","012"=>$_mdb->kingdee_shopnum);//借方 分类和 直营店
                        $datedai=array("008"=>$_out_list->kingdee_supper,"012"=>$_mdb->kingdee_shopnum);//供应商  直营店
                        $temp_type=3;
                    }else{
                        $msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
                        if(is_null($msk)){
                            Log::error("门店 ".$_mdb->id."现金科目异常");
                            continue 2;//有错误数据
                        }
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_out_list->implement_time." ".$ms->name." 配件入库，退货";
                        $inputdai["FExplanation"]=$_out_list->implement_time." ".$ms->name." 配件入库，退货";
                        $inputdai["FAccountID"]=$msk->acount;
                        $datejie=array("009"=>"","012"=>$_mdb->kingdee_shopnum);//借方 分类和 直营店
                        $datedai=array();//供应商  直营店
                        $temp_type=3;
                    }
                    
                }else{
                    if($_out_list->return_type==2){//如果是盘亏
                        $inputjie["FAccountID"]="1243";
                        $inputjie["FExplanation"]=$_out_list->implement_time." 负库存调整";
                        $inputdai["FExplanation"]=$_out_list->implement_time." 负库存调整";
                        $inputdai["FAccountID"]="5501.19";
                        $inputdai["FDC"]=1;
                        $datejie=array("009"=>"","012"=>$_mdb->kingdee_shopnum);//借方 分类和 直营店
                        $datedai=array("012"=>$_mdb->kingdee_shopnum);//供应商  直营店
                        $temp_type=4;
                    }else{//如果是其他 不计入
                        continue;//本单 不推凭证
                    }
                }                   
            }
            $count=DB::select("SELECT sc1.id,sc1.`name`,sc1.jindie_code,sum(moi.tax_purchase_subtotal) as amount
                FROM `maintenance_out_item` moi
                LEFT JOIN supply_item si ON moi.item_id = si.id
                LEFT JOIN supply_classification sc3 ON sc3.id = si.supply_classification_id
                LEFT JOIN supply_classification sc2 ON sc2.id = sc3.parent_id
                LEFT JOIN supply_classification sc1 ON sc1.id = sc2.parent_id
                WHERE list_id = ? and  moi.`status`=1 group by sc1.id",array($_out_list->id));
            $temp_out_array=array();
            foreach ($count as $_count) {
                if($temp_type==3){//出库挂账
                    $inputjie["FAmountFor"]=-round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=-round($_count->amount/100,2);
                    $datejie["009"]=$_count->jindie_code;
                    $inputjie["data"]=$datejie;
                    $temp_out_array[]=$inputjie;
                    $inputdai["FAmountFor"]=-round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=-round($_count->amount/100,2);
                    $inputdai["data"]=$datedai;
                    $temp_out_array[]=$inputdai;
                }else if($temp_type==4){//盘点
                    $inputjie["FAmountFor"]=-round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=-round($_count->amount/100,2);  
                    $datejie["009"]=$_count->jindie_code;                   
                    $inputjie["data"]=$datejie;
                    $temp_out_array[]=$inputjie;
                    $inputdai["FAmountFor"]=round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=round($_count->amount/100,2);
                    $inputdai["data"]=$datedai;
                    $temp_out_array[]=$inputdai;
                }else{
                    $inputjie["FAmountFor"]=round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=round($_count->amount/100,2);                      
                    $inputjie["data"]=$datejie;
                    $temp_out_array[]=$inputjie;
                    $inputdai["FAmountFor"]=round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=round($_count->amount/100,2);
                    $datedai["009"]=$_count->jindie_code;
                    $inputdai["data"]=$datedai;
                    $temp_out_array[]=$inputdai;
                }

            }
            if($_out_list->type==1&&$_out_list->methed==1){//如果是内部领用 合并借方
                $depe_temp_dai=null;
                foreach($temp_out_array as $key=>$t){
                    if($t['FDC']==1&&$t['FExplanation'] ==$_out_list->implement_time." 物料领用出库"){
                        if(is_null($depe_temp_dai)){
                            $depe_temp_dai=$t;
                        }else{
                            $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                            $depe_temp_dai["FAmount"]+=$t['FAmount'];
                        }
                        unset($temp_out_array[$key]);
                    }
                }
                $temp_iyc_amount=array();
                if(!is_null($depe_temp_dai)){
                    $temp_iyc_amount[]=$depe_temp_dai;
                }
                $temp_out_array=array_merge($temp_iyc_amount,$temp_out_array);
            }

            if($_out_list->type==1&&$_out_list->methed==2){//如果是调出 合并借方
                $depe_temp_dai=null;
                foreach($temp_out_array as $key=>$t){
                    if($t['FDC']==1){
                        if(is_null($depe_temp_dai)){
                            $depe_temp_dai=$t;
                        }else{
                            $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                            $depe_temp_dai["FAmount"]+=$t['FAmount'];
                        }
                        unset($temp_out_array[$key]);
                    }
                }
                $temp_iyc_amount=array();
                if(!is_null($depe_temp_dai)){
                    $temp_iyc_amount[]=$depe_temp_dai;
                }
                $temp_out_array=array_merge($temp_iyc_amount,$temp_out_array);
            }

            if($_out_list->type==2&&$_out_list->return_type==0){//如果是出库退货 合并贷方
                $depe_temp_dai=null;
                foreach($temp_out_array as $key=>$t){
                    if($t['FDC']==0){
                        if(is_null($depe_temp_dai)){
                            $depe_temp_dai=$t;
                        }else{
                            $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                            $depe_temp_dai["FAmount"]+=$t['FAmount'];
                        }
                        unset($temp_out_array[$key]);
                    }
                }
                // $temp_iyc_amount=array();
                // if(!is_null($depe_temp_dai)){
                //     $temp_iyc_amount[]=$depe_temp_dai;
                // }
                if(!is_null($depe_temp_dai)){
                    $temp_out_array[]=$depe_temp_dai;
                }
                // $temp_out_array=array_merge($temp_iyc_amount,$temp_out_array);
            }

            $out_entty_array[$_out_list->id]=$temp_out_array;
            $out_key_array[$_out_list->id]=sizeof($temp_out_array);
        }
        $data=assemble($data,$out_entty_array,$out_key_array,$date,$_mdb);
        unset($out_entty_array);
        unset($out_key_array);
        /**
         * 查找该店该天的出库数据完毕
         */   
        //盘点数据
        $pandidan_entty_array=array();
        $pandidan_key_array=array();
        $pandian_list=DB::select("select id,implement_time from maintenance_inventory_list where shop_id=?  and  implement_time BETWEEN ? and ? and  `status`=2
            ORDER BY `implement_time` ASC", array($_mdb->id,$begin_date, $end_date));
        foreach ($pandian_list as $_pd) {//循环入库记录 组织结构
            $inputdai["FDC"]=0;
            $count=DB::select("SELECT sc1.id,sc1.`name`,sc1.jindie_code,sum(msi.tax_purchase_price*mis.number) as amount
                FROM maintenance_inventory_storage mis 
                LEFT JOIN maintenance_storage_item msi on mis.storage_id=msi.id
                LEFT JOIN supply_item si ON msi.item_id = si.id
                LEFT JOIN supply_classification sc3 ON sc3.id = si.supply_classification_id
                LEFT JOIN supply_classification sc2 ON sc2.id = sc3.parent_id
                LEFT JOIN supply_classification sc1 ON sc1.id = sc2.parent_id
                WHERE mis.list_id = ? and  mis.`status`=1 group by sc1.id",array($_pd->id));
            $temp_out_array=array();
            foreach ($count as $_count) {
                if($_count->amount>0){//盘应 先借正数 再借负数 
                    $inputjie["FAccountID"]="1243";
                    $inputjie["FExplanation"]=$_pd->implement_time." 盘点盘盈";
                    $inputjie["FAmountFor"]=round($_count->amount/100,2);//修改借方 金额和借方的参与主体 分类和门店
                    $inputjie["FAmount"]=round($_count->amount/100,2);
                    $datejie=array("009"=>$_count->jindie_code,"012"=>$_mdb->kingdee_shopnum);//借方 分类和 直营店
                    $inputjie["data"]=$datejie;
                    $temp_out_array[]=$inputjie;

                    $inputdai["FAccountID"]="5501.19";
                    $inputdai["FExplanation"]=$_pd->implement_time." 盘点盘盈";
                    $inputdai["FAmountFor"]=-round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=-round($_count->amount/100,2);
                    $inputdai["FDC"]=1;
                    $datedai=array("012"=>$_mdb->kingdee_shopnum);//直营店
                    $inputdai["data"]=$datedai;
                    $temp_out_array[]=$inputdai;
                }else if($_count->amount<0){//盘亏 先借负数 再借正数
                    $inputjie["FAccountID"]="1243";
                    $inputjie["FExplanation"]=$_pd->implement_time." 盘点盘亏";
                    $inputjie["FAmountFor"]=round($_count->amount/100,2);//数据已经是负值 不用处理
                    $inputjie["FAmount"]=round($_count->amount/100,2);
                    $datejie=array("009"=>$_count->jindie_code,"012"=>$_mdb->kingdee_shopnum);//借方 分类和 直营店
                    $inputjie["data"]=$datejie;
                    $temp_out_array[]=$inputjie;

                    $inputdai["FAccountID"]="5501.19";
                    $inputdai["FExplanation"]=$_pd->implement_time." 盘点盘亏";
                    $inputdai["FAmountFor"]=-round($_count->amount/100,2);//修改贷方的信息
                    $inputdai["FAmount"]=-round($_count->amount/100,2);
                    $inputdai["FDC"]=1;
                    $datedai=array("012"=>$_mdb->kingdee_shopnum);//直营店
                    $inputdai["data"]=$datedai;
                    $temp_out_array[]=$inputdai;
                }
            }
            if(sizeof($temp_out_array)==0){//如果组合完成 该盘点单成本无变化
                continue;
            }
            $pandidan_entty_array[$_pd->id]=$temp_out_array;
            $pandidan_key_array[$_pd->id]=sizeof($temp_out_array);
        }
        $data=assemble($data,$pandidan_entty_array,$pandidan_key_array,$date,$_mdb);
        unset($pandidan_entty_array);
        unset($pandidan_key_array);
        
        // Log::info($data);
        if(sizeof($data["mainVoucher"])>0){  
            getMaintain($_mdb->id,$data,$date);
            Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
            echo "门店".$_mdb->id." 日期 ".$date.'完毕';
        }else{
            Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
            echo "门店".$_mdb->id." 日期 ".$date.'完毕';
        }  
        

          
    }
}



function assemble(&$finally,$value_array,$key_array,$date,$_mdb){
    if(sizeof($value_array)==0){//如果以及那个组合完成
        return $finally;
    }
    asort($key_array);//对 数组排序
    $temp_finally=sortAssemble(array(),$value_array,$key_array);
    foreach ($temp_finally as $_tf) {           
        $temp =array(
            "FDate"=>$date." 00:00:00",
            "FGroupID"=>$_mdb->kingdee_groupid,//来广营 6
            "FReference"=>null,
            "FAttachments"=>0,
            "FEntryCount"=>4,
            "FDebitTotal"=>0,
            "FCreditTotal"=>0,
            "FPreparerID"=>16428,//写死的制单人
            "FPosterID"=>-1,
            "FTranType"=>0,
            "FTransDate"=>$date." 00:00:00",
            "entryVoucher"=>array(
                
            )           
        );
        $FEntryCount=0;
        $FDebitTotal=0;
        $FCreditTotal=0;
        foreach ($_tf as $value) {  
            $FEntryCount++;
            $value["FAmountFor"]=round($value["FAmountFor"],2);
            $value["FAmount"]=round($value["FAmount"],2);
            if($value["FDC"]==1){
                $FDebitTotal+=$value["FAmountFor"];
            }else{
                $FCreditTotal+=$value["FAmountFor"];
            }                           
            $temp["entryVoucher"][]=$value;
        }
        $temp["FEntryCount"]=$FEntryCount;
        $temp["FDebitTotal"]=round($FDebitTotal,2);
        $temp["FCreditTotal"]=round($FCreditTotal,2);
        $finally["mainVoucher"][]=$temp;
    }
    return $finally;
}
    
function sortAssemble($finally,$value_array,$key_array){    
    if(sizeof($key_array)==0){//如果以及那个组合完成
        return $finally;
    }
    $temp_array=array();//临时存放 数组集合的数组
    end($key_array);//获取最后一个元素 也就是 数值最多的元素
    $key=key($key_array);//获取数组元素最多的键值
    $number=$key_array[$key];// 获取元素最多的键值 个数
    unset($key_array[$key]);
    foreach ($key_array as $nowkey=>$value) {
        if($number+$value>10){//说名 当前最大的 元素 已经没有 元素可以和他组合之后 数组数量不超过10
            $finally[]=$value_array[$key];
            unset($value_array[$key]);
            return sortAssemble($finally,$value_array,$key_array);//递归下一轮
        }else if($number+$value==10){//说名 当前最大的 元素 已经没有 元素可以和他组合之后 数组数量不超过10
            $temp=array_merge($value_array[$key],$value_array[$nowkey]);
            $finally[]=$temp;
            unset($value_array[$key]);
            unset($value_array[$nowkey]);
            unset($key_array[$nowkey]);
            return sortAssemble($finally,$value_array,$key_array);//递归下一轮
        }
    }
    //如果走到这个地方说明 剩余的数组中 和当前的数组 元素单个相加都不超过 10个
    //就叠加 剩下的元素 直至超过 大于等于10 这里选择先加小元素   
    $temp_array=$value_array[$key];
    unset($value_array[$key]);

    foreach ($key_array as $nowkey=>$value) {
        $temp_number=sizeof($temp_array);
        if($temp_number+$value>10){//说明上面 不能在添加这个元素
            $finally[]=$temp_array;
            return sortAssemble($finally,$value_array,$key_array);//递归下一轮
        }
        $temp_array=array_merge($temp_array,$value_array[$nowkey]);
        unset($value_array[$nowkey]);
        unset($key_array[$nowkey]);
    } 
    $finally[]=$temp_array;//说明添加完毕 都没有超过10条
    return $finally;
}


function getMaintain($shop_id,$data,$date){ 
    $request = array(
        'token' => 1,
        'zhangtao' => "sqlsrv_scs",
        'params' => json_encode($data),
    );

    $response = Httpful::post(Config::get('config.kingdee_local_api')."/kingdeescs/importVoucher")
        ->timeoutIn(15)
        ->body($request)
        ->sendsForm()->send();

    $response = json_decode($response->body);
    Log::info($response->msg);
    $kvs=new KingdeeVoucherStatus();
    $kvs->date=$date;
    $kvs->shop_id=$shop_id;
    $kvs->type="supply_inout";
    if($response->code==0){//说明成功
        $kvs->status=1;
    }else{
        $kvs->status=0;
    }
    $kvs->save();
}